const fs = require('fs');
const _ = require('lodash');
const Promise = require('bluebird');
const lineReader = require('line-reader');
const mysql = require('mysql2');
const models = require('../../src/models');
const mysqlConfig = require('../../config').mysql;

new Promise(function (resolve, reject) {
    /**
     * 创建数据库
     */
    var connection = mysql.createConnection({
        host: mysqlConfig.connection.host,
        user: mysqlConfig.username,
        password: mysqlConfig.password
    });
    connection.connect();
    connection.query('CREATE DATABASE IF NOT EXISTS ' + mysqlConfig.dbname, function (err, result) {
        console.log(result);
        if (err) {
            return reject({success: false});
        }
        return resolve({success: true});
    });
    connection.end();
}).then(function (result) {
    let instance = models.newInstance(mysqlConfig);
    let sequelize = instance.sequelize;

    return instance.Settings.count().then(function (count) {
        /**
         * 数据库表存在
         */
        console.log('初始化失败, 数据库表存在');
        return {success: false, message: '数据库表存在'};

    }, function (err) {
        /**
         * 数据库表不存在,创建数据库表和初始化数据
         */
        if (err.message.indexOf('doesn\'t exist') != -1) {
            return sequelize.sync().then(function () {
                console.log('Create tables has been successfully.');

                /**
                 * 初始化数据
                 */
                return sequelize.transaction(function (t) {
                    return instance.Settings.bulkCreate(require('./data/settings.json'), {transaction: t}).then(function () {
                        return instance.Dicts.bulkCreate(require('./data/dicts.json'), {transaction: t});
                    }).then(function () {
                        return instance.Articles.bulkCreate(require('./data/articles.json'), {transaction: t});
                    }).then(function () {
                        return instance.Users.registerV2({
                            "id": 1,
                            "tel": "13510946316",
                            "nickname": "guson",
                            "email": "gusonyang@qq.com",
                            "qq": "375339508",
                            "role": "SuperAdmin",
                            "status": "Active",
                            "password": "yangsg123"
                        });
                    }).then(function () {
                        return instance.Permissions.bulkCreate(require('./data/permissions.json'), {transaction: t});
                    }).then(function () {
                        var permissions_roles = require('./data/permissions_roles.json');
                        var excutes = [];
                        for (var i in permissions_roles) {
                            var permissions_role = permissions_roles[i];
                            var role = permissions_role.Role, permissions = permissions_role.Permissions;
                            for (var j in permissions) {
                                var permission = permissions[j];
                                var sql = "insert into PermissionsRoles(role, permission_id, created_at, updated_at) " +
                                    "select '" + role + "', id as permission_id, NOW(), NOW() from Permissions where object_type = '" + permission.object_type + "'";
                                if (permission.action_type != 'all') {
                                    sql += " and action_type in (" + permission.action_type + ")";
                                }
                                excutes.push(sequelize.query(sql, {
                                    type: sequelize.QueryTypes.INSERT, transaction: t
                                }));
                            }
                        }
                        return Promise.all(excutes);
                    }).then(function () {
                        let eachLine = Promise.promisify(lineReader.eachLine);
                        return eachLine(__dirname + '/data/init.sql', function (line) {
                            return sequelize.query(line);
                        });
                    });
                });
            }).then(function () {
                console.log('初始化成功');
                return {success: true};
            });
        } else {
            console.log('初始化失败', err.message);
            return {success: false, message: err.message};
        }
    });
});
